﻿using Microsoft.AspNetCore.Mvc;
using MyECommerceProject.Interfaces;
using MyECommerceProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyECommerceProject.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly IProductService _productService;
        private readonly IInventoryService _inventoryService;

        public ProductController(IProductService productService, IInventoryService inventoryService)
        {
            _productService = productService;
            _inventoryService = inventoryService;

        }
        //查询
        [HttpGet]
        public async Task<IEnumerable<Product>> GetProducts()
        {
            return await _productService.GetProductsAsync();
        }


        [HttpGet("{id}")]
        public async Task<Product> GetProduct(int id)
        {
            return await _productService.GetProductByIdAsync(id);
        }

        //增加
        [HttpPost]
        public async Task<IActionResult> AddProduct([FromBody] Product product)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            try
            {
                await _productService.AddProductAsync(product);

                // 自动生成库存记录
                var inventory = new Inventory
                {
                    ProductId = product.ProductID,
                    Sell = false,
                    Count = product.StockQuantity,
                    OperationDate = DateOnly.FromDateTime(DateTime.Now),
                    Product = product
                };

                await _inventoryService.AddInventoryAsync(inventory);

                return Ok();
            }
            catch (Exception ex)
            {
                // Log exception details
                Console.WriteLine(ex.Message);
                return StatusCode(500, "Internal server error");
            }
        }
        //删除
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProductAndinventory(int id)
        {
            await _productService.DeleteProductAsync(id);
            //await _inventoryService.DeleteInventoryAsync(id);只是删除商品本身，不删除库存记录
            return Ok();
        }

        //更改
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateProduct(int id, [FromBody] Product product)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            var existingProduct = await _productService.GetProductByIdAsync(id);
            if (existingProduct == null)
                return NotFound();

            product.ProductID = id;
            await _productService.UpdateProductAsync(product);
            return Ok();
        }

        //查询排序，待补充的分页查询
        [HttpGet("sorted")]
        public async Task<IEnumerable<Product>> GetProductsSorted(string sortBy, bool ascending = true)
        {
            Func<Product, object> keySelector = sortBy.ToLower() switch
            {
                "name" => p => p.Name,
                "price" => p => p.Price,
                "soldgoods" => p => p.SoldGoods,
                //"modifieddate" => p => p.ModifiedDate,
                _ => p => p.Name,
            };

            return await _productService.GetProductsSortedByAsync(keySelector, ascending);
        }

        //输出品类 按价格筛选

        [HttpPost("searchproduct")]
        public async Task<IEnumerable<Product>> GetProductsByOptionAsync(ProductSearchOption option)
        {

            return await _productService.GetProductsByOptionAsync(option);
        }



        //[HttpPost("{id}/sell")]
        //public async Task<IActionResult> SellProduct(int id, [FromBody] int quantity)
        //{
        //    if (quantity <= 0)
        //        return BadRequest("Quantity must be greater than zero.");

        //    var product = await _productService.GetProductByIdAsync(id);
        //    if (product == null)
        //        return NotFound("Product not found.");

        //    var inventory = await _inventoryService.GetInventoryByIdAsync(id);
        //    if (inventory == null)
        //        return NotFound("Inventory not found.");

        //    if (quantity > inventory.StockQuantity)
        //        return BadRequest("Insufficient stock.");

        //    product.Count += quantity;
        //    product.ModifiedDate = DateTime.UtcNow;

        //    inventory.StockQuantity -= quantity;
        //    inventory.LastUpdated = DateTime.UtcNow;

        //    await _productService.UpdateProductAsync(product);
        //    await _inventoryService.UpdateInventoryAsync(inventory);

        //    return Ok();
        //}

        //[HttpPost("{id}/name")]
        //public async Task<IActionResult> ChageProductNameAsync(int id, [FromQuery] string name)
        //{


        //    var product = await _productService.GetProductByIdAsync(id);


        //    //product.ModifiedDate = DateTime.Now;

        //    product.Name = name;

        //    await _productService.UpdateProductAsync(product);


        //    return Ok();
        //}

        //[HttpPost("{id}/restock")]
        //public async Task<IActionResult> RestockProduct(int id, [FromBody] int quantity)
        //{
        //    if (quantity <= 0)
        //        return BadRequest("Quantity must be greater than zero.");

        //    var inventory = await _inventoryService.GetInventoryByIdAsync(id);
        //    if (inventory == null)
        //        return NotFound("Inventory not found.");

        //    inventory.StockQuantity += quantity;
        //    inventory.LastUpdated = DateTime.UtcNow;

        //    await _inventoryService.UpdateInventoryAsync(inventory);

        //    return Ok();
        //}







        //[HttpGet("filtered")]
        //public async Task<IEnumerable<Product>> GetProductsFiltered(int? categoryId, bool? isAvailable)
        //{
        //    Func<Product, bool> predicate = p =>
        //    {
        //        bool matches = true;
        //        if (categoryId.HasValue)
        //            matches &= p.Category == categoryId;
        //        if (isAvailable.HasValue)
        //            matches &= p.IsAvailable == isAvailable;
        //        return matches;
        //    };

        //    return await _productService.GetProductsFilteredByAsync(predicate);
        //}



    }
}